﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Controls;

namespace SharpSoft.WPF
{
    public static class PrinterHelper
    {
        /// <summary>
        /// 打印指定的UI
        /// </summary>
        /// <param name="ele"></param>
        /// <param name="pageOrientation"></param>
        /// <param name="title"></param>
        public static void PrintVisual(this UIElement ele, PageOrientation pageOrientation, string title)
        {
            PrintDialog dialog = new PrintDialog();
            dialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
            PrintCapabilities capabilities = dialog.PrintQueue.GetPrintCapabilities(dialog.PrintTicket);
            Size sz = new Size(capabilities.PageImageableArea.ExtentWidth - capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.ExtentHeight - capabilities.PageImageableArea.OriginHeight);
            ele.Measure(sz);
            ele.Arrange(new Rect(new Point(0, 0), sz));
            var bmp = ele.Capture();
            Image image = new Image() { Width = sz.Width, Height = sz.Height, Stretch = Stretch.Fill, Source = bmp };

            double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / image.Width,
                             capabilities.PageImageableArea.ExtentHeight / image.Height);

            image.LayoutTransform = new ScaleTransform(scale, scale);


            image.Measure(sz);
            image.Arrange(new Rect(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight, capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.OriginHeight));

            dialog.PrintVisual(image, title);
        }
    }
}
